import {KJUR, KEYUTIL, hex2b64, b64tohex} from 'jsrsasign'

const RSA_NAME = process.env.VUE_APP_RSA_NAME;
const RSA_PUBKEY = process.env.VUE_APP_RSA_PUBKEY;
const RSA_PRIKEY = process.env.VUE_APP_RSA_PRIKEY;
// 签名算法
const ALGORITHM = 'SHA256withRSA'
const FORMAT_KEY = function (str = "",prefix = "PUBLIC") {
  let arr = [];
  if(str.indexOf("BEGIN")==-1){
    if(prefix == "PUBLIC"){
      arr.push("-----BEGIN PUBLIC KEY-----")
      arr.push(str)
      arr.push("-----END PUBLIC KEY-----")
    }else{
      arr.push("-----BEGIN PRIVATE KEY-----")
      arr.push(str)
      arr.push("-----END PRIVATE KEY-----")
    }
  }else{
    arr.push(str)
  }
  return arr.join('\n');
}

// 私钥签名
const RSA_SIGN = (privateKey, src) => {
  privateKey = FORMAT_KEY(privateKey,'PRIVATE')
  const signature = new KJUR.crypto.Signature({'alg': ALGORITHM})
  try{
    // 来解析密钥
    const priKey = KEYUTIL.getKey(privateKey)
    signature.init(priKey)
    // 传入待签明文
    signature.updateString(src)
    const a = signature.sign()
    // 转换成base64，返回
    return hex2b64(a)
  }catch (e) {
    alert('私钥签名 异常')
    throw new Error("私钥签名 异常");
  }
}

// 公钥验签
const RSA_VERIFY_SIGN = (publicKey, src, data) => {
  publicKey = FORMAT_KEY(publicKey,'PUBLIC');
  const signature = new KJUR.crypto.Signature({'alg': ALGORITHM, 'prvkeypem': publicKey})
  signature.updateString(src)
  return signature.verify(b64tohex(data))
}

function test(src = "123",publicKey = RSA_PUBKEY,privateKey = RSA_PRIKEY){
  // console.log(publicKey,privateKey)
  console.log('明文:', src)
  const data = RSA_SIGN(privateKey, src)
  console.log('签名后的结果:', data)
  const res = RSA_VERIFY_SIGN(publicKey, src, data)
  console.log('验签结果:', res)
  return data;
}

global.test = test;
export {
  RSA_SIGN,
  RSA_VERIFY_SIGN,
  RSA_NAME,
  test
}
